package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"soft-sys/cache"
	"soft-sys/models"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	img := c.PostForm("img")
	title := c.PostForm("title")
	content := c.PostForm("content")

	if img == "" || title == "" || content == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	data := models.Game{
		Img:     img,
		Title:   title,
		Content: content,
	}
	err := models.DB.Create(&data).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "下载失败",
		})
		return
	}
	redis_key := "game_" + strconv.Itoa(int(data.ID))
	var game models.Game
	models.DB.Where("id=?", data.ID).Find(&game)
	jsonData, _ := json.Marshal(game)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "下载成功",
	})
}
func List(c *gin.Context) {
	var game models.Game

	models.DB.Find(&game)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": game,
	})
}
